<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>班次管理 - 列车车次管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../css/admin.css" rel="stylesheet">
</head>
<body>
    <!-- 导航栏 -->    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="/admin/dashboard.html">
                <img src="/images/logo.jpeg" alt="Logo" class="admin-logo d-inline-block align-text-top">
                <i class="fas fa-train me-2"></i>列车车次管理系统
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="/admin/dashboard.html">
                            <i class="fas fa-tachometer-alt me-1"></i>仪表盘
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/admin/users.html">
                            <i class="fas fa-users me-1"></i>用户管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/admin/stations.html">
                            <i class="fas fa-map-marker-alt me-1"></i>车站管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/admin/trains.html">
                            <i class="fas fa-train me-1"></i>火车管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/admin/routes.html">
                            <i class="fas fa-route me-1"></i>线路管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="/admin/schedules.html">
                            <i class="fas fa-calendar-alt me-1"></i>班次管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/admin/tickets.html">
                            <i class="fas fa-ticket-alt me-1"></i>票务管理
                        </a>
                    </li>
                </ul>
                <ul class="navbar-nav">
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown">
                            <i class="fas fa-user me-1"></i><span id="adminName">管理员</span>
                        </a>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="/profile.html">个人资料</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="#" onclick="logout()">退出登录</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container-fluid mt-4">
        <div class="row">
            <div class="col-12">
                <!-- 页面标题 -->
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h2><i class="fas fa-calendar-alt me-2"></i>班次管理</h2>
                    <div>
                        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#scheduleModal" onclick="showAddScheduleModal()">
                            <i class="fas fa-plus me-1"></i>添加班次
                        </button>
                        <button class="btn btn-success" onclick="exportToCSV()">
                            <i class="fas fa-download me-1"></i>导出数据
                        </button>
                    </div>
                </div>

                <!-- 搜索和过滤器 -->
                <div class="card mb-4">
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-2">
                                <label for="searchTrainNumber" class="form-label">车次号</label>
                                <input type="text" class="form-control" id="searchTrainNumber" placeholder="输入车次号">
                            </div>
                            <div class="col-md-2">
                                <label for="searchDepartureStation" class="form-label">出发站</label>
                                <select class="form-select" id="searchDepartureStation">
                                    <option value="">全部出发站</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label for="searchArrivalStation" class="form-label">到达站</label>
                                <select class="form-select" id="searchArrivalStation">
                                    <option value="">全部到达站</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label for="searchDate" class="form-label">日期</label>
                                <input type="date" class="form-control" id="searchDate">
                            </div>
                            <div class="col-md-2">
                                <label for="filterStatus" class="form-label">状态</label>
                                <select class="form-select" id="filterStatus">
                                    <option value="">全部状态</option>
                                    <option value="正常">正常</option>
                                    <option value="晚点">晚点</option>
                                    <option value="停运">停运</option>
                                    <option value="取消">取消</option>
                                </select>
                            </div>
                            <div class="col-md-2 d-flex align-items-end">
                                <button class="btn btn-primary me-2" onclick="searchSchedules()">
                                    <i class="fas fa-search me-1"></i>搜索
                                </button>
                                <button class="btn btn-secondary" onclick="resetFilters()">
                                    <i class="fas fa-undo me-1"></i>重置
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 班次列表 -->
                <div class="card">
                    <div class="card-body">
                        <div id="loadingSpinner" class="text-center" style="display: none;">
                            <div class="spinner-border" role="status">
                                <span class="visually-hidden">加载中...</span>
                            </div>
                        </div>
                        
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead class="table-dark">
                                    <tr>
                                        <th>车次号</th>
                                        <th>出发站</th>
                                        <th>到达站</th>
                                        <th>出发时间</th>
                                        <th>到达时间</th>
                                        <th>运行时长</th>
                                        <th>票价信息</th>
                                        <th>状态</th>
                                        <th>创建时间</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="schedulesTableBody">
                                    <!-- 数据将通过JavaScript动态加载 -->
                                </tbody>
                            </table>
                        </div>

                        <!-- 分页 -->
                        <nav aria-label="分页导航">
                            <ul class="pagination justify-content-center" id="pagination">
                                <!-- 分页按钮将通过JavaScript动态生成 -->
                            </ul>
                        </nav>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加/编辑班次模态框 -->
    <div class="modal fade" id="scheduleModal" tabindex="-1" aria-labelledby="scheduleModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="scheduleModalLabel">添加班次</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="scheduleForm">
                        <input type="hidden" id="scheduleId">
                        
                        <!-- 基本信息 -->
                        <div class="row">
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label for="trainSelect" class="form-label">选择火车 <span class="text-danger">*</span></label>
                                    <select class="form-select" id="trainSelect" required>
                                        <option value="">请选择火车</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label for="routeSelect" class="form-label">选择线路 <span class="text-danger">*</span></label>
                                    <select class="form-select" id="routeSelect" required>
                                        <option value="">请选择线路</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label for="scheduleDate" class="form-label">班次日期 <span class="text-danger">*</span></label>
                                    <input type="date" class="form-control" id="scheduleDate" required>
                                </div>
                            </div>
                        </div>

                        <!-- 出发和到达信息 -->
                        <div class="row">
                            <div class="col-md-3">
                                <div class="mb-3">
                                    <label for="departureStation" class="form-label">出发站 <span class="text-danger">*</span></label>
                                    <select class="form-select" id="departureStation" required>
                                        <option value="">请选择出发站</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="mb-3">
                                    <label for="arrivalStation" class="form-label">到达站 <span class="text-danger">*</span></label>
                                    <select class="form-select" id="arrivalStation" required>
                                        <option value="">请选择到达站</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="mb-3">
                                    <label for="departureTime" class="form-label">出发时间 <span class="text-danger">*</span></label>
                                    <input type="time" class="form-control" id="departureTime" required>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="mb-3">
                                    <label for="arrivalTime" class="form-label">到达时间 <span class="text-danger">*</span></label>
                                    <input type="time" class="form-control" id="arrivalTime" required>
                                </div>
                            </div>
                        </div>

                        <!-- 票价信息 -->
                        <div class="card mb-3">
                            <div class="card-header">
                                <h6 class="mb-0">票价设置</h6>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-2">
                                        <div class="mb-3">
                                            <label for="hardSeatPrice" class="form-label">硬座价格</label>
                                            <div class="input-group">
                                                <span class="input-group-text">¥</span>
                                                <input type="number" class="form-control" id="hardSeatPrice" min="0" step="0.01">
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-2">
                                        <div class="mb-3">
                                            <label for="softSeatPrice" class="form-label">软座价格</label>
                                            <div class="input-group">
                                                <span class="input-group-text">¥</span>
                                                <input type="number" class="form-control" id="softSeatPrice" min="0" step="0.01">
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-2">
                                        <div class="mb-3">
                                            <label for="hardSleeperPrice" class="form-label">硬卧价格</label>
                                            <div class="input-group">
                                                <span class="input-group-text">¥</span>
                                                <input type="number" class="form-control" id="hardSleeperPrice" min="0" step="0.01">
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-2">
                                        <div class="mb-3">
                                            <label for="softSleeperPrice" class="form-label">软卧价格</label>
                                            <div class="input-group">
                                                <span class="input-group-text">¥</span>
                                                <input type="number" class="form-control" id="softSleeperPrice" min="0" step="0.01">
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-2">
                                        <div class="mb-3">
                                            <label for="businessSeatPrice" class="form-label">商务座价格</label>
                                            <div class="input-group">
                                                <span class="input-group-text">¥</span>
                                                <input type="number" class="form-control" id="businessSeatPrice" min="0" step="0.01">
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-2">
                                        <div class="mb-3">
                                            <label for="scheduleStatus" class="form-label">状态</label>
                                            <select class="form-select" id="scheduleStatus">
                                                <option value="正常">正常</option>
                                                <option value="晚点">晚点</option>
                                                <option value="停运">停运</option>
                                                <option value="取消">取消</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="saveSchedule()">
                        <i class="fas fa-save me-1"></i>保存
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 班次详情模态框 -->
    <div class="modal fade" id="scheduleDetailModal" tabindex="-1" aria-labelledby="scheduleDetailModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="scheduleDetailModalLabel">班次详情</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="scheduleDetailContent">
                    <!-- 详情内容将通过JavaScript动态生成 -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 删除确认模态框 -->
    <div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="deleteModalLabel">确认删除</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>您确定要删除班次 <strong id="deleteScheduleInfo"></strong> 吗？</p>
                    <p class="text-danger">此操作会同时删除该班次的所有订票记录，且不可撤销！</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-danger" onclick="confirmDelete()">
                        <i class="fas fa-trash me-1"></i>删除
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="../js/admin.js"></script>
    <script>
        let currentPage = 1;
        let totalPages = 1;
        let deleteScheduleId = null;
        let stations = [];
        let trains = [];
        let routes = [];

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            checkAdminAuth();
            loadStations();
            loadTrains();
            loadRoutes();
            loadSchedules();
            
            // 设置默认日期为今天
            document.getElementById('scheduleDate').value = new Date().toISOString().split('T')[0];
        });

        // 加载车站列表
        async function loadStations() {
            try {
                const response = await fetch('/api/stations', {
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    }
                });
                
                if (!response.ok) {
                    throw new Error('加载车站列表失败');
                }
                
                stations = await response.json();
                
                // 填充车站选择器
                const stationOptions = stations.map(station => 
                    `<option value="${station.id}">${station.stationName} (${station.stationCode})</option>`
                ).join('');
                
                document.getElementById('searchDepartureStation').innerHTML = '<option value="">全部出发站</option>' + stationOptions;
                document.getElementById('searchArrivalStation').innerHTML = '<option value="">全部到达站</option>' + stationOptions;
                document.getElementById('departureStation').innerHTML = '<option value="">请选择出发站</option>' + stationOptions;
                document.getElementById('arrivalStation').innerHTML = '<option value="">请选择到达站</option>' + stationOptions;
                
            } catch (error) {
                console.error('加载车站列表失败:', error);
                showAlert('加载车站列表失败', 'danger');
            }
        }

        // 加载火车列表
        async function loadTrains() {
            try {
                const response = await fetch('/api/trains', {
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    }
                });
                
                if (!response.ok) {
                    throw new Error('加载火车列表失败');
                }
                
                trains = await response.json();
                
                const trainOptions = trains.map(train => 
                    `<option value="${train.id}">${train.trainNumber} (${getTrainTypeLabel(train.trainType)})</option>`
                ).join('');
                
                document.getElementById('trainSelect').innerHTML = '<option value="">请选择火车</option>' + trainOptions;
                
            } catch (error) {
                console.error('加载火车列表失败:', error);
                showAlert('加载火车列表失败', 'danger');
            }
        }

        // 加载线路列表
        async function loadRoutes() {
            try {
                const response = await fetch('/api/routes', {
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    }
                });
                
                if (!response.ok) {
                    throw new Error('加载线路列表失败');
                }
                
                routes = await response.json();
                
                const routeOptions = routes.map(route => 
                    `<option value="${route.id}">${route.routeName}</option>`
                ).join('');
                
                document.getElementById('routeSelect').innerHTML = '<option value="">请选择线路</option>' + routeOptions;
                
            } catch (error) {
                console.error('加载线路列表失败:', error);
                showAlert('加载线路列表失败', 'danger');
            }
        }

        // 加载班次列表
        async function loadSchedules(page = 1) {
            try {
                showLoading(true);
                const searchTrainNumber = document.getElementById('searchTrainNumber').value;
                const searchDepartureStation = document.getElementById('searchDepartureStation').value;
                const searchArrivalStation = document.getElementById('searchArrivalStation').value;
                const searchDate = document.getElementById('searchDate').value;
                const filterStatus = document.getElementById('filterStatus').value;

                let url = `/api/schedules?page=${page - 1}&size=10`;
                
                if (searchTrainNumber) {
                    url += `&trainNumber=${encodeURIComponent(searchTrainNumber)}`;
                }
                if (searchDepartureStation) {
                    url += `&departureStationId=${searchDepartureStation}`;
                }
                if (searchArrivalStation) {
                    url += `&arrivalStationId=${searchArrivalStation}`;
                }
                if (searchDate) {
                    url += `&date=${searchDate}`;
                }
                if (filterStatus) {
                    url += `&status=${encodeURIComponent(filterStatus)}`;
                }

                const response = await fetch(url, {
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    }
                });
                
                if (!response.ok) {
                    throw new Error('加载班次列表失败');
                }
                
                const data = await response.json();
                displaySchedules(data.content || data);
                
                if (data.totalPages) {
                    totalPages = data.totalPages;
                    currentPage = page;
                    updatePagination();
                }
            } catch (error) {
                console.error('加载班次列表失败:', error);
                showAlert('加载班次列表失败', 'danger');
            } finally {
                showLoading(false);
            }
        }

        // 显示班次列表
        function displaySchedules(schedules) {
            const tbody = document.getElementById('schedulesTableBody');
            
            if (!schedules || schedules.length === 0) {
                tbody.innerHTML = '<tr><td colspan="10" class="text-center">暂无数据</td></tr>';
                return;
            }

            tbody.innerHTML = schedules.map(schedule => `
                <tr>
                    <td>
                        <strong>${schedule.trainNumber}</strong>
                        <br>
                        <small class="text-muted">
                            <a href="#" onclick="showScheduleDetail(${schedule.id})" class="text-decoration-none">
                                <i class="fas fa-info-circle me-1"></i>查看详情
                            </a>
                        </small>
                    </td>
                    <td>${getStationName(schedule.departureStationId)}</td>
                    <td>${getStationName(schedule.arrivalStationId)}</td>
                    <td>${formatDateTime(schedule.departureTime)}</td>
                    <td>${formatDateTime(schedule.arrivalTime)}</td>
                    <td>${calculateDuration(schedule.departureTime, schedule.arrivalTime)}</td>
                    <td>
                        <small>
                            ${formatPriceInfo(schedule)}
                        </small>
                    </td>
                    <td><span class="badge ${getStatusBadgeClass(schedule.status)}">${schedule.status}</span></td>
                    <td>${formatDateTime(schedule.createdAt)}</td>
                    <td>
                        <button class="btn btn-sm btn-outline-primary me-1" onclick="showEditScheduleModal(${schedule.id})" title="编辑">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-danger" onclick="showDeleteModal(${schedule.id}, '${schedule.trainNumber}')" title="删除">
                            <i class="fas fa-trash"></i>
                        </button>
                    </td>
                </tr>
            `).join('');
        }

        // 获取车站名称
        function getStationName(stationId) {
            const station = stations.find(s => s.id === stationId);
            return station ? `${station.stationName}` : '未知车站';
        }

        // 获取火车类型标签
        function getTrainTypeLabel(type) {
            const typeMap = {
                'G': '高速动车组(G)',
                'D': '动车组(D)',
                'C': '城际动车组(C)',
                'K': '快速列车(K)',
                'T': '特快列车(T)',
                'Z': '直达特快(Z)',
                '普通': '普通列车'
            };
            return typeMap[type] || type;
        }

        // 获取状态徽章样式
        function getStatusBadgeClass(status) {
            switch (status) {
                case '正常': return 'bg-success';
                case '晚点': return 'bg-warning';
                case '停运': return 'bg-danger';
                case '取消': return 'bg-secondary';
                default: return 'bg-secondary';
            }
        }

        // 格式化票价信息
        function formatPriceInfo(schedule) {
            const prices = [];
            if (schedule.hardSeatPrice) prices.push(`硬座:¥${schedule.hardSeatPrice}`);
            if (schedule.softSeatPrice) prices.push(`软座:¥${schedule.softSeatPrice}`);
            if (schedule.hardSleeperPrice) prices.push(`硬卧:¥${schedule.hardSleeperPrice}`);
            if (schedule.softSleeperPrice) prices.push(`软卧:¥${schedule.softSleeperPrice}`);
            if (schedule.businessSeatPrice) prices.push(`商务座:¥${schedule.businessSeatPrice}`);
            return prices.join('<br>') || '未设置';
        }

        // 计算运行时长
        function calculateDuration(departureTime, arrivalTime) {
            if (!departureTime || !arrivalTime) return '未知';
            
            const departure = new Date(departureTime);
            const arrival = new Date(arrivalTime);
            const diffMs = arrival - departure;
            
            if (diffMs < 0) return '时间错误';
            
            const hours = Math.floor(diffMs / (1000 * 60 * 60));
            const minutes = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60));
            
            return `${hours}小时${minutes}分钟`;
        }

        // 显示添加班次模态框
        function showAddScheduleModal() {
            document.getElementById('scheduleModalLabel').textContent = '添加班次';
            document.getElementById('scheduleForm').reset();
            document.getElementById('scheduleId').value = '';
            document.getElementById('scheduleStatus').value = '正常';
            document.getElementById('scheduleDate').value = new Date().toISOString().split('T')[0];
        }

        // 显示编辑班次模态框
        async function showEditScheduleModal(scheduleId) {
            try {
                const response = await fetch(`/api/schedules/${scheduleId}`, {
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    }
                });
                
                if (!response.ok) {
                    throw new Error('获取班次信息失败');
                }
                
                const schedule = await response.json();
                
                document.getElementById('scheduleModalLabel').textContent = '编辑班次';
                document.getElementById('scheduleId').value = schedule.id;
                document.getElementById('trainSelect').value = schedule.trainId;
                document.getElementById('routeSelect').value = schedule.routeId;
                document.getElementById('departureStation').value = schedule.departureStationId;
                document.getElementById('arrivalStation').value = schedule.arrivalStationId;
                
                // 处理日期和时间
                const departureDate = new Date(schedule.departureTime);
                const arrivalDate = new Date(schedule.arrivalTime);
                
                document.getElementById('scheduleDate').value = departureDate.toISOString().split('T')[0];
                document.getElementById('departureTime').value = departureDate.toTimeString().slice(0, 5);
                document.getElementById('arrivalTime').value = arrivalDate.toTimeString().slice(0, 5);
                
                // 票价信息
                document.getElementById('hardSeatPrice').value = schedule.hardSeatPrice || '';
                document.getElementById('softSeatPrice').value = schedule.softSeatPrice || '';
                document.getElementById('hardSleeperPrice').value = schedule.hardSleeperPrice || '';
                document.getElementById('softSleeperPrice').value = schedule.softSleeperPrice || '';
                document.getElementById('businessSeatPrice').value = schedule.businessSeatPrice || '';
                document.getElementById('scheduleStatus').value = schedule.status;
                
                new bootstrap.Modal(document.getElementById('scheduleModal')).show();
            } catch (error) {
                console.error('获取班次信息失败:', error);
                showAlert('获取班次信息失败', 'danger');
            }
        }

        // 保存班次
        async function saveSchedule() {
            try {
                const scheduleDate = document.getElementById('scheduleDate').value;
                const departureTime = document.getElementById('departureTime').value;
                const arrivalTime = document.getElementById('arrivalTime').value;
                
                const scheduleData = {
                    trainId: parseInt(document.getElementById('trainSelect').value),
                    routeId: parseInt(document.getElementById('routeSelect').value),
                    departureStationId: parseInt(document.getElementById('departureStation').value),
                    arrivalStationId: parseInt(document.getElementById('arrivalStation').value),
                    departureTime: `${scheduleDate}T${departureTime}:00`,
                    arrivalTime: `${scheduleDate}T${arrivalTime}:00`,
                    hardSeatPrice: parseFloat(document.getElementById('hardSeatPrice').value) || null,
                    softSeatPrice: parseFloat(document.getElementById('softSeatPrice').value) || null,
                    hardSleeperPrice: parseFloat(document.getElementById('hardSleeperPrice').value) || null,
                    softSleeperPrice: parseFloat(document.getElementById('softSleeperPrice').value) || null,
                    businessSeatPrice: parseFloat(document.getElementById('businessSeatPrice').value) || null,
                    status: document.getElementById('scheduleStatus').value
                };

                // 验证必填字段
                if (!scheduleData.trainId || !scheduleData.routeId || !scheduleData.departureStationId || 
                    !scheduleData.arrivalStationId || !scheduleData.departureTime || !scheduleData.arrivalTime) {
                    showAlert('请填写所有必填字段', 'warning');
                    return;
                }

                if (scheduleData.departureStationId === scheduleData.arrivalStationId) {
                    showAlert('出发站和到达站不能相同', 'warning');
                    return;
                }

                // 验证时间逻辑
                const depTime = new Date(scheduleData.departureTime);
                const arrTime = new Date(scheduleData.arrivalTime);
                if (arrTime <= depTime) {
                    showAlert('到达时间必须晚于出发时间', 'warning');
                    return;
                }

                const scheduleId = document.getElementById('scheduleId').value;
                const url = scheduleId ? `/api/schedules/${scheduleId}` : '/api/schedules';
                const method = scheduleId ? 'PUT' : 'POST';

                const response = await fetch(url, {
                    method: method,
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    },
                    body: JSON.stringify(scheduleData)
                });

                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.message || '保存失败');
                }

                showAlert(scheduleId ? '班次更新成功' : '班次添加成功', 'success');
                bootstrap.Modal.getInstance(document.getElementById('scheduleModal')).hide();
                loadSchedules(currentPage);
            } catch (error) {
                console.error('保存班次失败:', error);
                showAlert(error.message || '保存班次失败', 'danger');
            }
        }

        // 显示班次详情
        async function showScheduleDetail(scheduleId) {
            try {
                const response = await fetch(`/api/schedules/${scheduleId}`, {
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    }
                });
                
                if (!response.ok) {
                    throw new Error('获取班次详情失败');
                }
                
                const schedule = await response.json();
                
                const content = `
                    <div class="row">
                        <div class="col-md-6">
                            <h6>基本信息</h6>
                            <table class="table table-sm">
                                <tr><td>车次号</td><td>${schedule.trainNumber}</td></tr>
                                <tr><td>线路</td><td>${schedule.routeName}</td></tr>
                                <tr><td>出发站</td><td>${getStationName(schedule.departureStationId)}</td></tr>
                                <tr><td>到达站</td><td>${getStationName(schedule.arrivalStationId)}</td></tr>
                                <tr><td>出发时间</td><td>${formatDateTime(schedule.departureTime)}</td></tr>
                                <tr><td>到达时间</td><td>${formatDateTime(schedule.arrivalTime)}</td></tr>
                                <tr><td>运行时长</td><td>${calculateDuration(schedule.departureTime, schedule.arrivalTime)}</td></tr>
                                <tr><td>状态</td><td><span class="badge ${getStatusBadgeClass(schedule.status)}">${schedule.status}</span></td></tr>
                            </table>
                        </div>
                        <div class="col-md-6">
                            <h6>票价信息</h6>
                            <table class="table table-sm">
                                <tr><td>硬座</td><td>${schedule.hardSeatPrice ? '¥' + schedule.hardSeatPrice : '不提供'}</td></tr>
                                <tr><td>软座</td><td>${schedule.softSeatPrice ? '¥' + schedule.softSeatPrice : '不提供'}</td></tr>
                                <tr><td>硬卧</td><td>${schedule.hardSleeperPrice ? '¥' + schedule.hardSleeperPrice : '不提供'}</td></tr>
                                <tr><td>软卧</td><td>${schedule.softSleeperPrice ? '¥' + schedule.softSleeperPrice : '不提供'}</td></tr>
                                <tr><td>商务座</td><td>${schedule.businessSeatPrice ? '¥' + schedule.businessSeatPrice : '不提供'}</td></tr>
                            </table>
                        </div>
                    </div>
                `;
                
                document.getElementById('scheduleDetailContent').innerHTML = content;
                new bootstrap.Modal(document.getElementById('scheduleDetailModal')).show();
            } catch (error) {
                console.error('获取班次详情失败:', error);
                showAlert('获取班次详情失败', 'danger');
            }
        }

        // 显示删除模态框
        function showDeleteModal(scheduleId, trainNumber) {
            deleteScheduleId = scheduleId;
            document.getElementById('deleteScheduleInfo').textContent = trainNumber;
            new bootstrap.Modal(document.getElementById('deleteModal')).show();
        }

        // 确认删除
        async function confirmDelete() {
            try {
                const response = await fetch(`/api/schedules/${deleteScheduleId}`, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    }
                });

                if (!response.ok) {
                    throw new Error('删除失败');
                }

                showAlert('班次删除成功', 'success');
                bootstrap.Modal.getInstance(document.getElementById('deleteModal')).hide();
                loadSchedules(currentPage);
            } catch (error) {
                console.error('删除班次失败:', error);
                showAlert('删除班次失败', 'danger');
            }
        }

        // 搜索班次
        function searchSchedules() {
            currentPage = 1;
            loadSchedules();
        }

        // 重置过滤器
        function resetFilters() {
            document.getElementById('searchTrainNumber').value = '';
            document.getElementById('searchDepartureStation').value = '';
            document.getElementById('searchArrivalStation').value = '';
            document.getElementById('searchDate').value = '';
            document.getElementById('filterStatus').value = '';
            currentPage = 1;
            loadSchedules();
        }

        // 导出到CSV
        function exportToCSV() {
            const csvContent = generateCSVContent();
            downloadCSV(csvContent, 'schedules.csv');
        }

        function generateCSVContent() {
            const headers = ['车次号', '出发站', '到达站', '出发时间', '到达时间', '运行时长', '状态', '创建时间'];
            let csv = headers.join(',') + '\n';
            
            const rows = document.querySelectorAll('#schedulesTableBody tr');
            rows.forEach(row => {
                const cells = row.querySelectorAll('td');
                if (cells.length > 1) {
                    const rowData = [
                        cells[0].textContent.trim().split('\n')[0],
                        cells[1].textContent.trim(),
                        cells[2].textContent.trim(),
                        cells[3].textContent.trim(),
                        cells[4].textContent.trim(),
                        cells[5].textContent.trim(),
                        cells[7].textContent.trim(),
                        cells[8].textContent.trim()
                    ];
                    csv += rowData.join(',') + '\n';
                }
            });
            
            return csv;
        }

        function downloadCSV(content, filename) {
            const blob = new Blob(['\ufeff' + content], { type: 'text/csv;charset=utf-8;' });
            const link = document.createElement('a');
            const url = URL.createObjectURL(blob);
            link.setAttribute('href', url);
            link.setAttribute('download', filename);
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }

        // 更新分页
        function updatePagination() {
            const pagination = document.getElementById('pagination');
            let paginationHTML = '';

            // 上一页
            paginationHTML += `
                <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                    <a class="page-link" href="#" onclick="loadSchedules(${currentPage - 1})" aria-label="Previous">
                        <span aria-hidden="true">&laquo;</span>
                    </a>
                </li>
            `;

            // 页码
            for (let i = 1; i <= totalPages; i++) {
                if (i === currentPage || i === 1 || i === totalPages || (i >= currentPage - 1 && i <= currentPage + 1)) {
                    paginationHTML += `
                        <li class="page-item ${i === currentPage ? 'active' : ''}">
                            <a class="page-link" href="#" onclick="loadSchedules(${i})">${i}</a>
                        </li>
                    `;
                } else if (i === currentPage - 2 || i === currentPage + 2) {
                    paginationHTML += '<li class="page-item disabled"><a class="page-link">...</a></li>';
                }
            }

            // 下一页
            paginationHTML += `
                <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                    <a class="page-link" href="#" onclick="loadSchedules(${currentPage + 1})" aria-label="Next">
                        <span aria-hidden="true">&raquo;</span>
                    </a>
                </li>
            `;

            pagination.innerHTML = paginationHTML;
        }

        // 显示加载状态
        function showLoading(show) {
            document.getElementById('loadingSpinner').style.display = show ? 'block' : 'none';
        }

        // 格式化日期时间
        function formatDateTime(dateString) {
            if (!dateString) return '';
            const date = new Date(dateString);
            return date.toLocaleString('zh-CN');
        }

        // 显示提示信息
        function showAlert(message, type) {
            const alertDiv = document.createElement('div');
            alertDiv.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
            alertDiv.style.top = '20px';
            alertDiv.style.right = '20px';
            alertDiv.style.zIndex = '9999';
            alertDiv.innerHTML = `
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            `;
            document.body.appendChild(alertDiv);
            
            setTimeout(() => {
                if (alertDiv.parentNode) {
                    alertDiv.parentNode.removeChild(alertDiv);
                }
            }, 3000);
        }
    </script>
</body>
</html>
